package carassius.GUI;

import carassius.BLL.Events.Animal.AnimalAddedListener;
import carassius.BLL.Events.Animal.AnimalRemovedListener;
import carassius.BLL.Events.WaterCondition.WaterConditionAddedListener;
import carassius.BLL.Events.WaterCondition.WaterConditionRemovedListener;
import carassius.DAL.AnimalRow;
import carassius.DAL.Database;
import carassius.DAL.WaterConditionRow;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.Collection;
import java.util.ResourceBundle;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author siebz0r
 */
public class DatabaseForm
		extends JDialog
		implements AnimalAddedListener,
				   AnimalRemovedListener,
				   WaterConditionAddedListener,
				   WaterConditionRemovedListener
{
	//<editor-fold defaultstate="collapsed" desc="Constructors">
	public DatabaseForm(Window parent)
	{
		super(parent, ModalityType.APPLICATION_MODAL);
		Database.getAnimalTable().addAnimalAddedEventListener(this);
		Database.getAnimalTable().addAnimalRemovedEventListener(this);
		Database.getWaterConditionTable().addWaterConditionAddedListener(this);
		Database.getWaterConditionTable().addWaterConditionRemovedListener(this);
		initComponents();
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Private Methods">
	private void fillTab()
	{
		Component selectedComponent = uxMainTabbedPane.getSelectedComponent();
		if (selectedComponent == uxAnimalPanel)
		{
			fillAnimalTable();
		}
		else if (selectedComponent == uxWaterConditionPanel)
		{
			fillWaterConditionsList();
		}
	}

	private void fillAnimalTable()
	{
		try
		{
			DefaultTableModel model = (DefaultTableModel) uxAnimalTable.getModel();
			model.setRowCount(0);
			Collection<AnimalRow> animals = Database.getAnimalTable().getAll();
			for (AnimalRow animalRow : animals)
			{
				addAnimalToTable(animalRow);
			}
		}
		catch (SQLException ex)
		{
			//todo: handle
		}
	}

	private void fillWaterConditionsList()
	{
		try
		{
			DefaultListModel model = new DefaultListModel();
			Collection<WaterConditionRow> conditions = Database.getWaterConditionTable().getAll();

			for (WaterConditionRow row : conditions)
			{
				model.addElement(row);
			}
			uxWaterConditionsList.setModel(model);
		}
		catch (SQLException ex)
		{
			//todo: handle
		}
	}

	private void addAnimalToTable(AnimalRow row)
	{
		if (uxMainTabbedPane.getSelectedComponent() == uxAnimalPanel)
		{
			DefaultTableModel model = (DefaultTableModel) uxAnimalTable.getModel();
			model.addRow(new Object[]
					{
						row
					});
			int rowNumber = uxAnimalTable.getRowCount() - 1;
			Component renderer = uxAnimalTable.prepareRenderer(uxAnimalTable.getCellRenderer(rowNumber, 0), rowNumber, 0);
			uxAnimalTable.setRowHeight(rowNumber, renderer.getPreferredSize().height);
		}
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Public Methods">
	@Override
	public void dispose()
	{
		Database.getAnimalTable().removeAnimalAddedEventListener(this);
		Database.getAnimalTable().removeAnimalRemovedEventListener(this);
		Database.getWaterConditionTable().removeWaterConditionAddedListener(this);
		Database.getWaterConditionTable().removeWaterConditionRemovedListener(this);
		super.dispose();
	}
	//</editor-fold>

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        uxMainTabbedPane = new javax.swing.JTabbedPane();
        uxAnimalPanel = new javax.swing.JPanel();
        uxAddAnimalButton = new javax.swing.JButton();
        uxAnimalTableScrollPane = new javax.swing.JScrollPane();
        uxAnimalTable = new carassius.GUI.AnimalTable(this);
        uxWaterConditionPanel = new javax.swing.JPanel();
        uxWaterConditionsScrollPane = new javax.swing.JScrollPane();
        uxWaterConditionsList = new javax.swing.JList();
        uxAddConditionButton = new javax.swing.JButton();
        uxConditionNameTextField = new TextFieldWithMenu();
        uxConditionNamePrefixLabel = new javax.swing.JLabel();
        uxConditionDescriptionPanel = new javax.swing.JPanel();
        uxConditionDescriptionScrollPane = new javax.swing.JScrollPane();
        uxConditionDescriptionTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(carassius.CarassiusApp.class).getContext().getResourceMap(DatabaseForm.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        uxMainTabbedPane.setName("uxMainTabbedPane"); // NOI18N
        uxMainTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                uxMainTabbedPaneStateChanged(evt);
            }
        });

        uxAnimalPanel.setName("uxAnimalPanel"); // NOI18N
        uxAnimalPanel.setLayout(new java.awt.GridBagLayout());

        uxAddAnimalButton.setText(resourceMap.getString("uxAddAnimalButton.text")); // NOI18N
        uxAddAnimalButton.setName("uxAddAnimalButton"); // NOI18N
        uxAddAnimalButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uxAddAnimalButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        uxAnimalPanel.add(uxAddAnimalButton, gridBagConstraints);

        uxAnimalTableScrollPane.setName("uxAnimalTableScrollPane"); // NOI18N

        uxAnimalTable.setName("uxAnimalTable"); // NOI18N
        uxAnimalTableScrollPane.setViewportView(uxAnimalTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        uxAnimalPanel.add(uxAnimalTableScrollPane, gridBagConstraints);

        uxMainTabbedPane.addTab(resourceMap.getString("uxAnimalPanel.TabConstraints.tabTitle"), uxAnimalPanel); // NOI18N

        uxWaterConditionPanel.setName("uxWaterConditionPanel"); // NOI18N
        uxWaterConditionPanel.setLayout(new java.awt.GridBagLayout());

        uxWaterConditionsScrollPane.setName("uxWaterConditionsScrollPane"); // NOI18N

        uxWaterConditionsList.setName("uxWaterConditionsList"); // NOI18N
        uxWaterConditionsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                uxWaterConditionsListValueChanged(evt);
            }
        });
        uxWaterConditionsList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                uxWaterConditionsListKeyPressed(evt);
            }
        });
        uxWaterConditionsScrollPane.setViewportView(uxWaterConditionsList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 0.5;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
        uxWaterConditionPanel.add(uxWaterConditionsScrollPane, gridBagConstraints);

        uxAddConditionButton.setText(resourceMap.getString("uxAddConditionButton.text")); // NOI18N
        uxAddConditionButton.setName("uxAddConditionButton"); // NOI18N
        uxAddConditionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uxAddConditionButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        uxWaterConditionPanel.add(uxAddConditionButton, gridBagConstraints);

        uxConditionNameTextField.setName("uxConditionNameTextField"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
        uxWaterConditionPanel.add(uxConditionNameTextField, gridBagConstraints);

        uxConditionNamePrefixLabel.setText(resourceMap.getString("uxConditionNamePrefixLabel.text")); // NOI18N
        uxConditionNamePrefixLabel.setName("uxConditionNamePrefixLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 0);
        uxWaterConditionPanel.add(uxConditionNamePrefixLabel, gridBagConstraints);

        uxConditionDescriptionPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("uxConditionDescriptionPanel.border.title"))); // NOI18N
        uxConditionDescriptionPanel.setName("uxConditionDescriptionPanel"); // NOI18N
        uxConditionDescriptionPanel.setLayout(new javax.swing.BoxLayout(uxConditionDescriptionPanel, javax.swing.BoxLayout.LINE_AXIS));

        uxConditionDescriptionScrollPane.setName("uxConditionDescriptionScrollPane"); // NOI18N

        uxConditionDescriptionTextArea.setColumns(20);
        uxConditionDescriptionTextArea.setLineWrap(true);
        uxConditionDescriptionTextArea.setRows(5);
        uxConditionDescriptionTextArea.setName("uxConditionDescriptionTextArea"); // NOI18N
        uxConditionDescriptionScrollPane.setViewportView(uxConditionDescriptionTextArea);

        uxConditionDescriptionPanel.add(uxConditionDescriptionScrollPane);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.gridheight = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 0.5;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        uxWaterConditionPanel.add(uxConditionDescriptionPanel, gridBagConstraints);

        uxMainTabbedPane.addTab("Waterwaardes", uxWaterConditionPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(uxMainTabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(uxMainTabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void uxAddAnimalButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uxAddAnimalButtonActionPerformed
	{//GEN-HEADEREND:event_uxAddAnimalButtonActionPerformed
		AnimalForm af = new AnimalForm(this);
		af.setVisible(true);
	}//GEN-LAST:event_uxAddAnimalButtonActionPerformed

	private void uxAddConditionButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uxAddConditionButtonActionPerformed
	{//GEN-HEADEREND:event_uxAddConditionButtonActionPerformed
		String name = uxConditionNameTextField.getText().trim();
		String desc = uxConditionDescriptionTextArea.getText().trim();

		try
		{
			if (uxWaterConditionsList.getSelectedValue() instanceof WaterConditionRow)
			{
				WaterConditionRow row = (WaterConditionRow) uxWaterConditionsList.getSelectedValue();
				if (row.getName().equals(uxConditionNameTextField.getText()))
				{
					row.setDescription(uxConditionDescriptionTextArea.getText());
				}
			}
			else
			{
				Database.getWaterConditionTable().add(name, desc);
			}
		}
		catch (SQLException ex)
		{
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterConditionsError"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterConditionsErrorTitle"),
					JOptionPane.ERROR_MESSAGE);
		}
}//GEN-LAST:event_uxAddConditionButtonActionPerformed

	private void uxMainTabbedPaneStateChanged(javax.swing.event.ChangeEvent evt)//GEN-FIRST:event_uxMainTabbedPaneStateChanged
	{//GEN-HEADEREND:event_uxMainTabbedPaneStateChanged
		fillTab();
	}//GEN-LAST:event_uxMainTabbedPaneStateChanged

	private void uxWaterConditionsListValueChanged(javax.swing.event.ListSelectionEvent evt)//GEN-FIRST:event_uxWaterConditionsListValueChanged
	{//GEN-HEADEREND:event_uxWaterConditionsListValueChanged
		if (evt.getValueIsAdjusting())
		{
			if (uxWaterConditionsList.getSelectedValue() instanceof WaterConditionRow)
			{
				WaterConditionRow row = (WaterConditionRow) uxWaterConditionsList.getSelectedValue();
				uxConditionNameTextField.setText(row.getName());
				uxConditionNameTextField.setEnabled(false);
				uxConditionDescriptionTextArea.setText(row.getDescription());
				uxAddConditionButton.setText("Opslaan");
			}
			else
			{
				uxConditionNameTextField.setText(null);
				uxConditionNameTextField.setEnabled(true);
				uxConditionDescriptionTextArea.setText(null);
				uxAddConditionButton.setText("Toevoegen");
			}
		}
	}//GEN-LAST:event_uxWaterConditionsListValueChanged

	private void uxWaterConditionsListKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_uxWaterConditionsListKeyPressed
	{//GEN-HEADEREND:event_uxWaterConditionsListKeyPressed
		if (evt.getKeyCode() == KeyEvent.VK_ESCAPE)
		{
			uxWaterConditionsList.clearSelection();
			uxWaterConditionsListValueChanged(null);
		}
		else if (evt.getKeyCode() == KeyEvent.VK_DELETE)
		{
			Object[] selectedValues = uxWaterConditionsList.getSelectedValues();
			if (selectedValues.length > 0)
			{
				if (JOptionPane.showConfirmDialog(this,
						ResourceBundle.getBundle("carassius.resources.Messages").getString("RemoveWaterConditions"),
						ResourceBundle.getBundle("carassius.resources.Messages").getString("RemoveWaterConditionsTitle"),
						JOptionPane.YES_NO_OPTION,
						JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION)
				{
					for (Object obj : selectedValues)
					{
						try
						{
							if (obj instanceof WaterConditionRow)
							{
								Database.getWaterConditionTable().delete((WaterConditionRow) obj);
							}
						}
						catch (SQLException ex)
						{
							JOptionPane.showMessageDialog(this,
									ResourceBundle.getBundle("carassius.resources.Messages").getString("RemoveWaterConditionsError"),
									ResourceBundle.getBundle("carassius.resources.Messages").getString("RemoveWaterConditionsErrorTitle"),
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			}
		}
	}//GEN-LAST:event_uxWaterConditionsListKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton uxAddAnimalButton;
    private javax.swing.JButton uxAddConditionButton;
    private javax.swing.JPanel uxAnimalPanel;
    private carassius.GUI.AnimalTable uxAnimalTable;
    private javax.swing.JScrollPane uxAnimalTableScrollPane;
    private javax.swing.JPanel uxConditionDescriptionPanel;
    private javax.swing.JScrollPane uxConditionDescriptionScrollPane;
    private javax.swing.JTextArea uxConditionDescriptionTextArea;
    private javax.swing.JLabel uxConditionNamePrefixLabel;
    private javax.swing.JTextField uxConditionNameTextField;
    private javax.swing.JTabbedPane uxMainTabbedPane;
    private javax.swing.JPanel uxWaterConditionPanel;
    private javax.swing.JList uxWaterConditionsList;
    private javax.swing.JScrollPane uxWaterConditionsScrollPane;
    // End of variables declaration//GEN-END:variables

	//<editor-fold defaultstate="collapsed" desc="Events">
	//<editor-fold defaultstate="collapsed" desc="Animal">
	@Override
	public void animalAdded(AnimalRow row)
	{
		addAnimalToTable(row);
	}

	@Override
	public void animalRemoved(AnimalRow row)
	{
		if (uxMainTabbedPane.getSelectedComponent() == uxAnimalPanel)
		{
			DefaultTableModel model = (DefaultTableModel) uxAnimalTable.getModel();
			for (int i = model.getRowCount() - 1; i >= 0; i--)
			{
				if (row.equals(model.getValueAt(i, 0)))
				{
					uxAnimalTable.getCellEditor(i, 0).cancelCellEditing();
					model.removeRow(i);
				}
			}
		}
	}
	//</editor-fold>

	@Override
	public void waterConditionAdded(WaterConditionRow row)
	{
		if (uxMainTabbedPane.getSelectedComponent() == uxWaterConditionPanel)
		{
			DefaultListModel model = (DefaultListModel) uxWaterConditionsList.getModel();
			model.addElement(row);
		}
	}

	@Override
	public void waterConditionRemoved(WaterConditionRow row)
	{
		if (uxMainTabbedPane.getSelectedComponent() == uxWaterConditionPanel)
		{
			DefaultListModel model = (DefaultListModel) uxWaterConditionsList.getModel();
			model.removeElement(row);
		}
	}
	//</editor-fold>
}
